<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>ISBN扫码测试</title>
    <!-- 使用ZXing库 -->
    <script src="https://unpkg.com/@zxing/library@latest/umd/index.min.js"></script>
    <!-- 备用CDN源 -->
    <script>
        // 检查ZXing是否已加载，如果没有则尝试备用源
        window.addEventListener('DOMContentLoaded', function() {
            if (typeof ZXing === 'undefined') {
                console.log('主CDN加载失败，尝试备用源');
                var script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/@zxing/library@latest/umd/index.min.js';
                script.onload = function() {
                    console.log('备用CDN加载成功');
                    document.getElementById('status').textContent = '扫描器加载成功，请点击开始扫描';
                };
                script.onerror = function() {
                    console.error('备用CDN也加载失败');
                    document.getElementById('status').textContent = '扫描器加载失败，请检查网络连接';
                    // 尝试本地加载
                    var localScript = document.createElement('script');
                    localScript.src = '/node_modules/@zxing/library/umd/index.min.js';
                    localScript.onload = function() {
                        console.log('本地库加载成功');
                        document.getElementById('status').textContent = '扫描器加载成功，请点击开始扫描';
                    };
                    localScript.onerror = function() {
                        document.getElementById('status').textContent = '所有扫描器加载尝试均失败，请刷新页面重试';
                    };
                    document.head.appendChild(localScript);
                };
                document.head.appendChild(script);
            } else {
                console.log('主CDN加载成功');
                document.getElementById('status').textContent = '扫描器加载成功，请点击开始扫描';
            }
        });
    </script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 640px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
        }
        .scanner-container {
            max-width: 640px;
            margin: 0 auto;
            position: relative;
            width: 100%;
            box-shadow: 0 0 20px rgb(0 0 0 / 30%);
            border-radius: 12px;
            overflow: hidden;
            font-size: 0;
            height: 466px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        #preview-area {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            background-color: #f8f9fa;
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        #preview-area:hover {
            border-color: #4CAF50;
            background-color: #f0f8f0;
        }
        #preview-area.dragover {
            border-color: #4CAF50;
            background-color: #e8f5e8;
            transform: scale(1.02);
        }
        #upload-prompt {
            text-align: center;
            color: #6c757d;
            padding: 40px 20px;
        }
        .upload-icon {
            font-size: 48px;
            margin-bottom: 16px;
        }
        .file-info {
            font-size: 14px;
            color: #adb5bd;
            margin-top: 8px;
        }
        #preview-image {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            border-radius: 8px;
        }
        #canvas {
            display: none;
        }
        .status {
            position: absolute;
            top: 50px;
            width: 100%;
            text-align: center;
            color: #fff;
            font-size: 16px;
            text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
            z-index: 10;
        }
        .controls {
            margin-top: 20px;
            text-align: center;
        }
        .btn {
            padding: 10px 20px;
            margin: 0 5px;
            border: none;
            border-radius: 5px;
            background-color: #4CAF50;
            color: white;
            font-size: 16px;
            cursor: pointer;
        }
        .btn-cancel {
            background-color: #f44336;
        }
        .result-container {
            margin-top: 20px;
            padding: 15px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .result-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        .result-item:last-child {
            border-bottom: none;
        }
        .success {
            color: #4CAF50;
        }
        .error {
            color: #f44336;
        }
        .stats {
            margin-top: 15px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>ISBN扫码测试 - 文件选择版本</h1>
            <p>选择图片文件进行ISBN条码识别</p>
        </div>
        
        <div class="scanner-container">
            <div id="preview-area">
                <div id="upload-prompt">
                    <div class="upload-icon">📷</div>
                    <p>点击选择图片或拖拽图片到此处</p>
                    <p class="file-info">支持 JPG、PNG、WEBP 格式</p>
                </div>
                <img id="preview-image" style="display: none;" />
                <canvas id="canvas" style="display: none;"></canvas>
            </div>
            <div id="status" class="status">扫描器已就绪，请选择图片</div>
        </div>
        
        <div class="controls">
            <input type="file" id="file-input" accept="image/*" style="display: none;">
            <button id="select-button" class="btn">选择图片</button>
            <button id="scan-button" class="btn" disabled>开始识别</button>
            <button id="clear-button" class="btn">清除结果</button>
        </div>
        
        <div class="result-container">
            <h2>扫描结果</h2>
            <div id="results"></div>
            <div id="stats" class="stats">
                总扫描次数: 0 | 成功: 0 | 失败: 0 | 成功率: 0%
            </div>
        </div>
    </div>
    
    <script>
        // 统计数据
        const stats = {
            total: 0,
            success: 0,
            failed: 0
        };
        
        // 获取DOM元素
        const selectButton = document.getElementById('select-button');
        const scanButton = document.getElementById('scan-button');
        const clearButton = document.getElementById('clear-button');
        const fileInput = document.getElementById('file-input');
        const previewArea = document.getElementById('preview-area');
        const uploadPrompt = document.getElementById('upload-prompt');
        const previewImage = document.getElementById('preview-image');
        const canvas = document.getElementById('canvas');
        const resultsContainer = document.getElementById('results');
        const statsContainer = document.getElementById('stats');
        const statusText = document.getElementById('status');
        
        // 全局变量
        let codeReader = null;
        let selectedFile = null;
        let isScanning = false;
        
        // ISBN校验函数
        const validateISBN = (code) => {
            if (code.length !== 13 && code.length !== 10) return false;
            // 这里可以添加更详细的校验逻辑
            return /^\d+$/.test(code);
        };
        
        // 更新统计信息
        const updateStats = () => {
            const successRate = stats.total > 0 ? Math.round((stats.success / stats.total) * 100) : 0;
            statsContainer.innerHTML = `总扫描次数: ${stats.total} | 成功: ${stats.success} | 失败: ${stats.failed} | 成功率: ${successRate}%`;
        };
        
        // 添加结果到列表
        const addResult = (code, isSuccess) => {
            stats.total++;
            if (isSuccess) {
                stats.success++;
            } else {
                stats.failed++;
            }
            
            const resultItem = document.createElement('div');
            resultItem.className = `result-item ${isSuccess ? 'success' : 'error'}`;
            resultItem.innerHTML = `
                <div>${new Date().toLocaleTimeString()}</div>
                <div>${isSuccess ? '成功' : '失败'}: ${code || '未识别'}</div>
            `;
            
            resultsContainer.insertBefore(resultItem, resultsContainer.firstChild);
            updateStats();
        };
        
        // 初始化ZXing扫描器
        const initializeScanner = () => {
            if (typeof ZXing === 'undefined') {
                statusText.textContent = '扫描器未加载，请刷新页面重试';
                console.error('ZXing未定义，无法初始化扫描器');
                return false;
            }
            
            if (!codeReader) {
                codeReader = new ZXing.BrowserMultiFormatReader();
                console.log('ZXing扫描器初始化成功');
            }
            return true;
        };
        
        // 处理文件选择
        const handleFileSelect = (file) => {
            if (!file) return;
            
            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                statusText.textContent = '请选择有效的图片文件';
                return;
            }
            
            selectedFile = file;
            
            // 创建文件读取器
            const reader = new FileReader();
            reader.onload = (e) => {
                // 显示预览图片
                previewImage.src = e.target.result;
                previewImage.style.display = 'block';
                uploadPrompt.style.display = 'none';
                
                // 启用扫描按钮
                scanButton.disabled = false;
                statusText.textContent = '图片已加载，点击开始识别';
            };
            
            reader.onerror = () => {
                statusText.textContent = '图片加载失败，请重新选择';
            };
            
            reader.readAsDataURL(file);
        };
        
        // 扫描图片函数
        const scanImage = async () => {
            if (!selectedFile || isScanning) {
                return;
            }
            
            if (!initializeScanner()) {
                return;
            }
            
            isScanning = true;
            scanButton.disabled = true;
            statusText.textContent = '正在识别图片...';
            
            try {
                console.log('开始识别图片:', selectedFile.name);
                
                // 使用预览图片进行识别
                const result = await codeReader.decodeOnce(previewImage);
                
                if (result) {
                    const code = result.getText();
                    console.log('检测到条码:', code);
                    
                    const isValid = validateISBN(code);
                    addResult(code, isValid);
                    
                    if (isValid) {
                        console.log('成功扫描到ISBN:', code);
                        statusText.textContent = `识别成功: ${code}`;
                        // 播放成功提示音
                        const audio = new Audio('data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBSuBzvLZiTYIG2m98OScTgwOUarm7blmGgU7k9n1unEiBC13yO/eizEIHWq+8+OWT');
                        audio.play().catch(() => {}); // 忽略音频播放错误
                    } else {
                        statusText.textContent = `识别到条码但非有效ISBN: ${code}`;
                    }
                } else {
                    addResult('未识别到条码', false);
                    statusText.textContent = '未识别到条码，请选择包含条码的图片';
                }
                
            } catch (error) {
                console.error('识别错误:', error);
                addResult('识别出错', false);
                statusText.textContent = '识别出错，请重新尝试';
            } finally {
                isScanning = false;
                scanButton.disabled = false;
            }
        };
        
        // 重置选择状态
        const resetSelection = () => {
            selectedFile = null;
            previewImage.style.display = 'none';
            uploadPrompt.style.display = 'block';
            scanButton.disabled = true;
            statusText.textContent = '扫描器已就绪，请选择图片';
        };
        
        // 处理拖拽事件
        const handleDragOver = (e) => {
            e.preventDefault();
            previewArea.classList.add('dragover');
        };
        
        const handleDragLeave = (e) => {
            e.preventDefault();
            previewArea.classList.remove('dragover');
        };
        
        const handleDrop = (e) => {
            e.preventDefault();
            previewArea.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFileSelect(files[0]);
            }
        };
        
        // 清除结果
        const clearResults = () => {
            resultsContainer.innerHTML = '';
            stats.total = 0;
            stats.success = 0;
            stats.failed = 0;
            updateStats();
        };
        
        // 事件监听器
        selectButton.addEventListener('click', () => {
            fileInput.click();
        });
        
        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                handleFileSelect(file);
            }
        });
        
        scanButton.addEventListener('click', scanImage);
        clearButton.addEventListener('click', clearResults);
        
        // 拖拽事件监听
        previewArea.addEventListener('dragover', handleDragOver);
        previewArea.addEventListener('dragleave', handleDragLeave);
        previewArea.addEventListener('drop', handleDrop);
        
        // 点击预览区域也可以选择文件
        previewArea.addEventListener('click', () => {
            if (!selectedFile) {
                fileInput.click();
            }
        });
        
        // 双击预览区域重新选择文件
        previewArea.addEventListener('dblclick', () => {
            resetSelection();
            fileInput.click();
        });
    </script>
</body>
</html>